<template>
  <el-dialog draggable :close-on-click-modal="false" v-model="dialogVisible" :title="dialogTitle" width="600px">
    <el-form :model="formData" ref="formRef" :rules="rules" label-width="100px">
      <el-form-item label="园区名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入园区名称" />
      </el-form-item>
      <!-- <el-form-item label="所在城市" prop="city">
        <el-select v-model="formData.city" placeholder="请选择城市">
          <el-option v-for="city in cities" :key="city" :label="city" :value="city" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入详细地址" />
      </el-form-item>
      <el-form-item label="占地面积" prop="area">
        <el-input v-model.number="formData.area" placeholder="请输入占地面积" type="number" />
        <template #append>㎡</template>
      </el-form-item>
      <el-form-item label="园区描述">
        <el-input v-model="formData.description" placeholder="请输入园区描述" type="textarea" rows="4" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, inject } from 'vue';
import { ElMessage,ElLoading } from 'element-plus';
import request from '@/api/request'

// 状态管理
const dialogVisible = ref(false);
const dialogTitle = ref('新增园区');
const formData = ref({});
const formRef = ref(null);

// // 城市列表
// const cities = ref([
//   '贵阳', '六盘水'
// ]);

// 验证规则
const rules = ref({
  name: [{ required: true, message: '请输入园区名称', trigger: 'blur' }],
  // city: [{ required: true, message: '请选择所在城市', trigger: 'change' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  area: [
    { required: true, message: '请输入占地面积', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === null || value === undefined) {
          callback(new Error('请输入占地面积'));
        } else if (typeof value !== 'number' || value < 0) {
          callback(new Error('占地面积必须大于等于0'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 注入主组件的数据和方法
const parkData = inject('parkData'); // 实际应用中应该通过API操作
const emit = defineEmits(['success']);


let submitSuccessCallback = null;

// 打开弹窗
const open = (data, callback) => {
  submitSuccessCallback = callback
  if (data) {
    formData.value = { ...data };
    dialogTitle.value = '编辑园区';
  } else {
    formData.value = {
      name: '',
      // city: '',
      address: '',
      area: 0,
      description: ''
    };
    dialogTitle.value = '新增园区';
  }
  dialogVisible.value = true;
};
// 保存数据
const handleSave = async () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        text: '正在处理...',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      if (formData.value.id) {
        request.post('/park/modify', formData.value).then(data => {
          dialogVisible.value = false;
         loading.close()
          if (data.success) {
            ElMessage.success(data.message);
            emit('success');
            // 提交成功后调用上层传入的回调
            if (submitSuccessCallback) {
              submitSuccessCallback("parkList");
            }
          } else {
            ElMessage.success(data.message);
            emit('fail');
          }
        }).catch(error => {
          loading.close()
          ElMessage.error('编辑异常', error)
        });
      } else {
        // 新增
        request.post('/park/add', formData.value).then(data => {
          dialogVisible.value = false;
         loading.close()
          if (data.success) {
            ElMessage.success(data.message);
            emit('success');
            // 提交成功后调用上层传入的回调
            if (submitSuccessCallback) {
              submitSuccessCallback("parkList");
            }
          } else {
            ElMessage.success(data.message);
            emit('fail');
          }
        }).catch(error => {
         loading.close()
          ElMessage.error('编辑异常', error)
        });
      }
    }
  });
};

// 暴露方法
defineExpose({
  open
});
</script>
